package com.bifang.module.file.dao;

import cn.hutool.core.date.DateUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.setting.Setting;
import com.bifang.engine.assistant.core.utils.PinyinUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lvxk
 * @date 2022-06-14
 * @description 数据字典生成枚举类
 */
public class GenerateEnum {

    public static void main(String[] args) throws SQLException {

        // sys_dict的dict_field值
        String dictField = "schoolcategory";
        String author = "lvxk";

        String url =
                "jdbc:mysql://118.31.228.198:3310/dyedu?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
        String driver = "com.mysql.cj.jdbc.Driver";
        String username = "dyedu";
        String password = "epsoft123";

        Setting setting = new Setting();
        setting.set("url", url);
        setting.set("driver", driver);
        setting.set("username", username);
        setting.set("password", password);
        DataSource dataSource = DSFactory.create(setting).getDataSource();
        String sql;
        if (dictField.contains(",")) {
            sql =
                    "select * from sys_dict where del='0' and dict_field in ('"
                            + Arrays.stream(dictField.split(","))
                                    .map(String::toUpperCase)
                                    .collect(Collectors.joining("','"))
                            + "')";
        } else {
            sql =
                    "select * from sys_dict where del='0' and dict_field ='"
                            + dictField.toUpperCase()
                            + "'";
        }
        List<Entity> dictList = DbUtil.use(dataSource).query(sql);
        Map<String, List<Entity>> dictMap =
                dictList.stream()
                        .collect(Collectors.groupingBy(item -> (String) item.get("dict_field")));
        dictMap.forEach(
                (key, value) -> {
                    System.out.println(value.size());
                    // 参数值
                    Map<String, Object> map = new HashMap<>();
                    Set<String> checkSet = new HashSet<>();
                    map.put("enumName", key.toUpperCase());
                    map.put("enumComment", value.get(0).get("field_name"));
                    map.put("author", author);
                    map.put("date", DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
                    value.forEach(
                            item -> {
                                String dictValue = (String) item.get("dict_value");
                                if (PinyinUtil.isChinese(dictValue)) {
                                    String enumKey = PinyinUtil.getAllFirstLetter(dictValue);
                                    if (checkSet.contains(enumKey)) {
                                        enumKey = enumKey + 1;
                                    }
                                    checkSet.add(enumKey);
                                    item.set("enumKey", enumKey);
                                } else {
                                    String enumKey = String.join("", dictValue.split("-"));
                                    if (checkSet.contains(enumKey)) {
                                        enumKey = enumKey + 1;
                                    }
                                    checkSet.add(enumKey);
                                    item.set("enumKey", enumKey);
                                }
                            });
                    map.put("entityList", value);
                    map.put("entitySize", value.size());
                    // 模板目录
                    String templateDirectory =
                            System.getProperty("user.dir")
                                    + "/bifang-base/bifang-base-common/src/main/resources/templatesFreemaker";
                    // 模板名称
                    String templateFile = "enum.java.ftl";
                    // 模板生成后存放目录
                    String targetPath =
                            System.getProperty("user.dir")
                                    + "/bifang-base/bifang-base-common/src/main/java/com/bifang/common/constant/enums/common";
                    // 模板生成后新文件名
                    String fileName = map.get("enumName") + "Enum.java";
                    // 创建文件夹
                    File nFile = new File(targetPath + "/" + fileName);
                    //                    if (nFile.exists()) {
                    //                        throw new RuntimeException("File '" + fileName + "'
                    // already exists");
                    //                    }
                    // 生成目标文件
                    try (Writer writer = new FileWriter(nFile)) {

                        Template template =
                                getConfiguration(templateDirectory)
                                        .getTemplate(templateFile, "UTF-8");
                        template.process(map, writer);

                    } catch (IOException | TemplateException e) {
                        throw new RuntimeException(e);
                    }
                });
    }

    private static Configuration getConfiguration(String templateDirectory) {

        Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
        try {
            configuration.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
            configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return configuration;
    }
}
